<template>
    <view>
        <!-- pages/setDiscount/setDiscount.wxml -->
        <view class="tabs">
            <van-dropdown-menu :active-color="mainColor">
                <van-dropdown-item :value="storeId" :options="stores" :disabled="storeId ? true : false" @change="storeDropdown" />
            </van-dropdown-menu>
        </view>
        <view class="container" :style="isIpx ? 'padding-bottom:168rpx' : 'padding-bottom:120rpx'">
            <block v-if="list.length">
                <view class="list">
                    <view :class="item.status === 2 ? 'item disabled' : 'item'" v-for="(item, index) in list" :key="index">
                        <view class="info">
                            <view class="line">
                                <label>适用门店：</label>
                                <text>{{ item.storeName }}</text>
                            </view>
                            <view class="line">
                                <label>充值金额：</label>
                                <text>{{ item.payMoney }}元</text>
                            </view>
                            <view class="line">
                                <label>赠送金额：</label>
                                <text>{{ item.giftMoney }}元</text>
                            </view>
                            <view class="line">
                                <label>创建时间：</label>
                                <text>{{ item.createTime }}</text>
                            </view>
                            <view class="line">
                                <label>过期时间：</label>
                                <text>{{ item.expriceTime }}</text>
                            </view>
                        </view>

                        <view class="btns">
                            <button hover-class="button-click" :class="item.status == 1 ? 'btn red' : 'btn green'" v-if="item.status != 2" @tap="setStatus" :data-info="item">
                                {{ item.status == 1 ? '禁用' : '启用' }}
                            </button>
                            <button hover-class="button-click" class="btn bg-primary" @tap="edit" :data-info="item">修改</button>
                        </view>
                    </view>
                </view>
                <view class="noteMore">下拉刷新加载更多</view>
            </block>
            <block v-else>
                <view class="nodata">暂无数据</view>
            </block>
        </view>
        <!-- 底部按钮 -->
        <view :class="'bottom bg-primary ' + (isIpx ? 'fix-iphonex-button' : '')" @tap="edit">添加规则</view>

        <!-- 修改弹窗 -->
        <van-dialog use-slot title="填写规则" :show="show" show-cancel-button @confirm="submit" @cancel="cancel" :before-close="beforeCloseFunction" zIndex="99">
            <view class="dialog">
                <van-cell-group>
                    <van-field label="适用门店：" placeholder="请选择门店" :border="false">
                        <picker slot="input" @change="bindStoreChange" range-key="text" :value="optionindex" :range="stores" :disabled="storeId ? true : false">
                            <view class="picker">
                                <input type="text" disabled placeholder="请选择门店" placeholder-class="plh" v-model="stores[optionindex].text" />
                            </view>
                        </picker>
                    </van-field>
                    <van-field v-model="payMoney" label="充值金额：" placeholder="请输入" type="digit" />
                    <van-field v-model="giftMoney" label="赠送金额：" placeholder="请输入" type="digit" />
                    <van-field label="过期时间：" placeholder="请选择时间">
                        <view slot="input" class="picker">
                            <picker style="width: 100%" mode="date" :value="expriceTime" @change="selectDateSecondChange">
                                <input type="text" disabled placeholder="请选择时间" placeholder-class="plh" v-model="expriceTime" />
                            </picker>
                        </view>
                    </van-field>
                </van-cell-group>
            </view>
        </van-dialog>
    </view>
</template>

<script>
// pages/setDiscount/setDiscount.js
const app = getApp();
var http = require('../../../utils/http');
var util1 = require('../../../utils/util.js');
export default {
    data() {
        return {
            show: false,

            //添加规则弹窗
            cityName: '',

            storeId: 0,

            //列表搜索门店id
            stores: [],

            pageNo: 1,
            pageSize: 10,
            canLoadMore: true,

            //是否还能加载更多
            list: [],

            payMoney: '',
            giftMoney: '',
            expriceTime: '',
            optionindex: '',
            storeId2: '',

            //添加修改时选择的门店id
            discountId: '',

            beforeCloseFunction: null,
            isIpx: app.globalData.isIpx ? true : false,
            mainColor: app.globalData.mainColor,
            text: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {
        this.setData({
            beforeCloseFunction: this.beforeClose()
        });
        this.setData({
            storeId: Number(options.storeId),
            storeId2: Number(options.storeId)
        });
        this.getXiaLaListAdmin();
        this.getMainListdata('refresh');
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        let that = this;
        this.setData({
            pageNo: 1,
            canLoadMore: true,
            list: []
        });
        this.getListData('refresh');
        uni.stopPullDownRefresh();
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        let that = this;
        if (that.canLoadMore) {
            that.pageNo++;
            this.getListData('');
        } else {
            uni.showToast({
                title: '我是有底线的...'
            });
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        //管理员获取门店下拉列表数据
        getXiaLaListAdmin: function (e) {
            var that = this;
            //if (app.globalData.isLogin)
            {
                http.request(
                    '/member/store/getStoreList',
                    '1',
                    'get',
                    {},
                    app.globalData.userDatatoken.accessToken,
                    '',
                    function success(info) {
                        console.info('下拉门店数据===');
                        console.info(info);
                        if (info.code == 0) {
                            let stores = [];
                            let optionindex = '';
                            info.data.map((it, index) => {
                                stores.push({
                                    text: it.key,
                                    value: it.value
                                });
                                if (it.value === that.storeId) {
                                    optionindex = index;
                                }
                            });
                            //console.log(optionindex)
                            that.setData({
                                stores: stores,
                                //  storeId: stores[0].value,
                                optionindex: optionindex
                            });
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        //门店下拉菜单发生变化
        storeDropdown(event) {
            //console.log(event)
            this.stores.map((it) => {
                if (it.value == event.detail) {
                    this.setData({
                        storeId: it.value
                    });
                }
            });
            this.getMainListdata('refresh');
        },

        //获取列表数据
        getMainListdata: function (e) {
            var that = this;
            let message = '';
            if (app.globalData.isLogin) {
                if (e == 'refresh') {
                    //刷新，page变为1
                    message = '正在加载';
                    that.setData({
                        pageNo: 1
                    });
                }
                http.request(
                    '/member/store/getDiscountRulesPage',
                    '1',
                    'post',
                    {
                        pageNo: that.pageNo,
                        pageSize: that.pageSize,
                        storeId: that.storeId
                    },
                    app.globalData.userDatatoken.accessToken,
                    message,
                    function success(info) {
                        console.info('返回111===');
                        console.info(info);
                        if (info.code == 0) {
                            if (e == 'refresh') {
                                that.setData({
                                    list: info.data.list
                                });
                                if (info.data.list.length === 0) {
                                    that.setData({
                                        canLoadMore: false
                                    });
                                }
                            } else {
                                if (info.data != null || info.data.list.length <= info.data.total) {
                                    that.setData({
                                        canLoadMore: false
                                    });
                                }
                                let arr = that.list;
                                let arrs = arr.concat(info.data.list);
                                that.setData({
                                    list: arrs
                                });
                            }
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        // 启用禁用
        setStatus: function (e) {
            let discountId = e.currentTarget.dataset.info.discountId;
            let that = this;
            if (app.globalData.isLogin) {
                http.request(
                    '/member/store/changeDiscountRulesStatus/' + discountId,
                    '1',
                    'post',
                    {},
                    app.globalData.userDatatoken.accessToken,
                    '',
                    function success(info) {
                        console.info('返回111===');
                        console.info(info);
                        if (info.code == 0) {
                            uni.showToast({
                                title: '设置成功'
                            });
                            that.getMainListdata('refresh');
                        } else {
                            uni.showModal({
                                content: info.msg,
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        // 获取优惠详情
        getData: function (discountId) {
            let that = this;
            if (app.globalData.isLogin) {
                http.request(
                    '/member/store/getDiscountRuleDetail/' + discountId,
                    '1',
                    'get',
                    {},
                    app.globalData.userDatatoken.accessToken,
                    '',
                    function success(info) {
                        console.info('返回111===');
                        console.info(info);
                        if (info.code == 0) {
                            let optionindex = '';
                            that.stores.map((it, index) => {
                                if (it.value === info.data.storeId) {
                                    optionindex = index;
                                }
                            });
                            that.setData({
                                payMoney: info.data.payMoney,
                                giftMoney: info.data.giftMoney,
                                expriceTime: info.data.expriceTime,
                                storeId2: info.data.storeId,
                                optionindex: optionindex
                            });
                        } else {
                            uni.showModal({
                                content: '请求服务异常，请稍后重试',
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        },

        // 修改弹窗
        edit: function (e) {
            if (e.currentTarget.dataset.info) {
                let discountId = e.currentTarget.dataset.info.discountId;
                this.setData({
                    discountId: discountId
                });
                this.getData(discountId);
            } else {
                this.setData({
                    discountId: '',
                    // optionindex: '',
                    payMoney: '',
                    giftMoney: '',
                    expriceTime: ''
                });
            }
            this.setData({
                show: true
            });
        },

        // 时分秒的事件方法
        selectDateSecondChange(e) {
            this.setData({
                expriceTime: e.detail.value
            });
        },

        // 弹窗选门店
        bindStoreChange: function (e) {
            this.setData({
                storeId2: this.stores[e.detail.value].value,
                optionindex: e.detail.value
            });
        },

        beforeClose() {
            // 这里一定要用箭头函数，否则访问不到this
            return (type) => {
                //console.log(type)
                if (type === 'cancel') {
                    // 点击取消
                    return true;
                } else {
                    // 点击确定
                }
            };
        },

        // 保存
        submit: function () {
            if (this.optionindex === '' || !this.payMoney || !this.giftMoney || !this.expriceTime) {
                uni.showToast({
                    title: '请填写完整',
                    icon: 'none'
                });
                return false;
            } else {
                this.updateData(this.discountId);
            }
        },

        // 取消
        cancel: function () {
            this.setData({
                // optionindex: '',
                payMoney: '',
                giftMoney: '',
                expriceTime: ''
            });
        },

        // 修改调接口
        updateData: function (discountId) {
            let that = this;
            if (app.globalData.isLogin) {
                http.request(
                    '/member/store/saveDiscountRuleDetail',
                    '1',
                    'post',
                    {
                        discountId: discountId ? discountId : '',
                        storeId: that.storeId2,
                        payMoney: that.payMoney,
                        giftMoney: that.giftMoney,
                        expriceTime: that.expriceTime
                    },
                    app.globalData.userDatatoken.accessToken,
                    '保存中',
                    function success(info) {
                        console.info('返回111===');
                        console.info(info);
                        if (info.code == 0) {
                            that.getMainListdata('refresh');
                            uni.showToast({
                                title: '设置成功'
                            });
                            that.setData({
                                show: false
                            });
                        } else {
                            uni.showModal({
                                content: info.msg,
                                showCancel: false
                            });
                        }
                    },
                    function fail(info) {}
                );
            }
        }
    }
};
</script>
<style>
@import './setDiscount.css';
</style>
